package com.zhkeshe.keshe.Service;

import com.zhkeshe.keshe.entity.CommonResult;
import com.zhkeshe.keshe.entity.Device;
import com.zhkeshe.keshe.entity.User;
import com.zhkeshe.keshe.entity.UserDevice;
import com.zhkeshe.keshe.mapper.DeviceMapper;
import com.zhkeshe.keshe.mapper.UserDeviceMapper;
import com.zhkeshe.keshe.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDeviceMapper userDeviceMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    public CommonResult loginService(Map<String, String> data){
        String useName=data.get("userName");
        String Password=data.get("Password");
        System.out.println(useName+Password);
        User user=userMapper.selectByUserName(useName);
        if(user!=null){//数据库有对应用户
            if(user.getPassword().equals(Password)){
                List<UserDevice> userDevices=userDeviceMapper.selectByUserId(user.getId());
                List<Device> deviceList=new ArrayList<>();
                for(UserDevice e:userDevices){
                    deviceList.add(deviceMapper.selectById(Long.parseLong(e.getDeviceId())));
                }
                System.out.println(deviceList);
                return new CommonResult(true,"登录成功",deviceList);
            }else return new CommonResult(false,"密码错误",new ArrayList<>());
        }else return new CommonResult(false,"用户未注册",new ArrayList<>());
    }

    public CommonResult register(Map<String, String> data){
        String useName=data.get("UserName");
        String Password=data.get("Password");
        User user=userMapper.selectByUserName(useName);
        if(user!=null){//数据库有对应用户
            return new CommonResult(false,"用户已注册",new ArrayList<>());
        }else {//无用户调用注册服务
            User user1=new User();
            user1.setUserName(useName);
            user1.setPassword(Password);
            userMapper.insertUser(user1);
            return new CommonResult(true,"注册成功",new ArrayList<>());
        }
    }
}
